#!/bin/sh
#
# publish -- put the token map in .vnc-tokens/local_map
#
# Copyright (C) 2016-2020 Wu Zhangjin <lzufalcon@163.com>
#

uname | grep -q MINGW && PWD_OPT="-W"
TOP_DIR="$(cd "$(dirname "$0")"/../../ && pwd $PWD_OPT)"
. "$TOP_DIR"/tools/docker/config $* >/dev/null

do_unlock
[ -z "$VNC_IP" ] && get_var VNC_IP
[ -z "$VNC_TOKEN" ] && get_var VNC_TOKEN
do_lock

# SUDO only required while the map is created in WPROXY
SUDO=""

map="${VNC_TOKEN}: ${VNC_IP}:5900"

# Touch token map files
touch_token_map

[ ! -f "$LOCAL_TOKEN_MAP" ] && $SUDO sh -c "echo $map > $LOCAL_TOKEN_MAP" && exit 0

grep -q "$map" "$LOCAL_TOKEN_MAP"
if [ $? -ne 0 ]; then
  grep ${VNC_TOKEN} "$LOCAL_TOKEN_MAP"
  [ $? -eq 0 ] && $SUDO sed -i -e "/${VNC_TOKEN}: /d" "$LOCAL_TOKEN_MAP"
  $SUDO sh -c "echo $map >> $LOCAL_TOKEN_MAP"
fi
